<?php

namespace Kangcg\Application\File;
/**
 * @desc 将数组写入文件
 * Class ArrayWriteFile
 * @package Kang\Libs\Helper
 */
class ArrayWriteFile
{
    public static $nbsp = '    ';

    public function getInstall()
    {
        if (self::$_install === null) {
            self::$_install = new self();
        }

        return self::$_install;
    }

    /**
     * 数组数据写入
     * @param array $data
     * @param string $filename
     * @param string $start
     * @param bool $isReturn true 文本内容返回 | false 写入
     * @return false|int|string
     */
    public function write(array $data, $filename, $start = "<?php \nreturn", $isReturn = false)
    {
        $content = $start . " [\n";
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $content .= self::$nbsp;
                $content .= is_numeric($key) ? $this->getBody($val) . ",\n" : ("'{$key}' => " . $this->getBody($val) . ",\n");
                continue;
            }

            if (is_bool($val)) {
                $val = $val ? 'true' : 'false';
                $content .= (self::$nbsp . "'{$key}' => {$val},\n");
                continue;
            }

            if (strpos($val, '\'')) {
                $content .= (self::$nbsp . "'{$key}' => \"{$val}\",\n");
            } else {
                $content .= (self::$nbsp . "'{$key}' => '{$val}',\n");
            }
        }

        $content .= '];';
        return $isReturn ? $content : file_put_contents($filename, $content);
    }

    private function getBody(array $data, $storey = 1)
    {
        $content = "[\n";
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $content .= $this->storey($storey + 1);
                if (!is_numeric($key)) {
                    $content .= "'{$key}' => ";
                }

                $content .= ($this->getBody($val, $storey + 1)) . ",\n";
                continue;
            }

            $content .= $this->storey($storey + 1);
            $val = is_bool($val) ? ($val ? 'true' : 'false') : "'{$val}'";
            $content .= ("'{$key}' => {$val},\n");
        }

        $content .= $this->storey($storey) . "]";
        return $content;
    }

    private function storey($storey)
    {
        $str = '';
        do {
            $str .= self::$nbsp;
            $storey--;
        } while ($storey > 0);

        return $str;
    }

    private static $_install = null;
}
